package com.ruoyi.framework.interceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @ClassName JwtHelperInterface
 * @Description TODO
 * @Author tyc@yanyu
 * @Date 2018/12/29 0029 15:30
 **/
public interface JwtHelperInterface {

    String audience = "098f6bcd4621d373cade4e832627b4f6";
    String secretKey = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";
    String issuer = "restapiuser";
    long expires = 24 * 3600 * 1000L;

    /**
     * 解析jwt
     */
    default Claims parseJwt(String jwtToken) throws Exception {
        return Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
                .parseClaimsJws(jwtToken).getBody();
    }
    /**
     * @param memberId   用户ID
     * @return jwt
     */
    default String createJwt(Long memberId) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("type", "JWT")
                .claim("memberId", memberId)
                .setIssuer(issuer)
                .setAudience(audience)
                .signWith(signatureAlgorithm, signingKey);

        //添加Token过期时间
        if (expires >= 0) {
            long expMillis = nowMillis + expires;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        return builder.compact();
    }
}
